package com.crm.util;

import java.net.URL;
import java.sql.Connection;
import java.util.Properties;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration;

public class ApplicationContext {
	Properties config;
	private static Connection con;
	private static Session sess;
	private static SessionFactory sessionFactory;
	public static SessionFactory getHiberSession() throws Exception{
		if(sessionFactory!=null){
			System.out.println("sessionFactory is conected "+ sessionFactory.isClosed());

		}
		
		if(sessionFactory==null){
			if(sessionFactory!=null)
				System.out.println("the session is not null"+sessionFactory);
			sessionFactory = new AnnotationConfiguration().configure(getConfigURL("crmhibernate.cfg.xml")).buildSessionFactory();
		}
		return sessionFactory;
	}
	private static URL getConfigURL(String fil) {
		URL url = ApplicationContext.class.getClassLoader().getResource(fil);
		if(url!=null) return url;
		url=ApplicationContext.class.getClassLoader().getResource(fil);
		if(url == null){
			url=ApplicationContext.class.getResource(fil);
		}
	 return url;	
	}
	/*public static Connection getConnnection() {
		if(con==null){
			try {
				Class.forName("com.mysql.jdbc.Driver");
				con=DriverManager.getConnection("jdbc:mysql://ec2-174-129-9-255.compute-1.amazonaws.com:3306/crmdb","crmuser","CRM4321");
			} catch (Exception e) {
						e.printStackTrace();
			}
			System.out.println("Connection made");
		}
		return con;
	}*/
	
	
	
	public String toString(){
		return super.toString();
	}
	public Properties getConfig() {
		return config;
	}
	public void setConfig(Properties config) {
		this.config = config;
	}
	public static Session getSess() {
		return sess;
	}
	public void setSess(Session sess) {
		ApplicationContext.sess = sess;
	}
	/**
	 * @return the mainMap
	 */
	
	public static void cleanUp(){
		try{
			if(con!=null)con.close();
			if(sess!=null)sess.close();
		}catch(Exception e){
			e.printStackTrace();
		}
		System.out.println("Cleanip done");
	}
	
	
}
